<template>
  <div class="file-show">
    <van-cell
      class="file-show-item"
      center
      v-for="(item, i) in value"
      :key="i"
      :title="item.name"
      @click="openFile(item)"
    >
      <template #icon>
        <svg-icon
          :iconClass="formatFile(item.name).svg"
          class="file-show-img"
        />
      </template>
      <template #right-icon v-if="isEdit">
        <div v-if="item.url" @click.stop="clickDelete(i)">
          <van-icon name="close" class="delete-icon" />
        </div>
        <van-loading v-else type="spinner" size="15px">正在上传</van-loading>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { formatFile } from "../../../utils/index";
import { downloadFile } from "@/api/data";
import { Toast } from "vant";
export default {
  props: {
    // 回显的文件列表
    value: {
      type: Array,
      default: () => [],
    },
    // 可编辑
    isEdit: {
      type: Boolean,
      default: false,
    },
    // 	下载的文件字段名
    dName: {
      type: String,
      default: "",
    },
    // 文件下载地址
    download: {
      type: String,
      default: "",
    },
    readonly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      list: this.value,
    };
  },

  methods: {
    formatFile,
    openFile(item) {
      if (!item.url) {
        return;
      }
      // 文件下载
      let formDate = new FormData();
      formDate.append(this.dName, item.id);
      Toast.loading({ forbidClick: true, duration: 15000 });
      downloadFile(
        this.download,
        formDate,
        () => {
          setTimeout(() => {
            Toast.clear();
          }, 500);
        },
        (msg) => {
          Toast.fail("下载失败");
        }
      );
    },

    // 删除文件
    clickDelete(i) {
      if (this.readonly) return;
      const newFiles = this.value.filter((item, index) => index !== i);
      this.$emit("update:value", newFiles);
      this.$emit("change", newFiles);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/style/color";
.file-show {
  width: 100%;
  box-sizing: border-box;
  .file-show-item {
    text-align: left;
    cursor: pointer;
    background-color: rgba($color: $blue, $alpha: 0.05);
    border-radius: 4px;
    padding: 8px;
    margin-bottom: 8px;
    .file-show-img {
      font-size: 25px;
      margin-right: 5px;
    }
    .delete-icon {
      font-size: 22px;
      color: red;
    }
    .van-loading {
      white-space: nowrap; //禁止换行
      .van-loading__text {
        font-size: 12px;
        color: $blue;
      }
    }
  }
  .file-show-item:last-child {
    margin-bottom: 0px;
  }
}
</style>
